<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery/jquery-3.3.1.js"></script>
    <script src="js/ol-debug.js"></script>
    <link rel="stylesheet" href="js/ol.css">
    <script src="popup/popup.js"></script>
    <link rel="stylesheet" href="popup/popup.css">
    <style>
        body{
            width: 100%;
            height: 100%;
            padding: 0px;
            margin: 0px;
        }
        #map-measure{
            position: absolute;
            z-index: 10;
            left: 100px;
            top:30px;
        }
        /*测量样式*/
        .tooltip {
            position: relative;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 4px;
            color: white;
            padding: 4px 8px;
            opacity: 0.7;
            white-space: nowrap;
        }
        .tooltip-measure {
            opacity: 1;
            font-weight: bold;
        }
        .tooltip-static {
            background-color: #ffcc33;
            color: black;
            border: 1px solid white;
        }
        .tooltip-measure:before,
        .tooltip-static:before {
            border-top: 6px solid rgba(0, 0, 0, 0.5);
            border-right: 6px solid transparent;
            border-left: 6px solid transparent;
            content: "";
            position: absolute;
            bottom: -6px;
            margin-left: -7px;
            left: 50%;
        }
        .tooltip-static:before {
            border-top-color: #ffcc33;
        }
        #map-switch{
            position:absolute;
            top: 50px;
            right: 50px;
            z-index: 10;
            padding: 10px;
            background-color: #ddccac;
            /*阴影*/
            box-shadow: 5px 5px 3px #888888;
            /*边框*/
            border:1px solid #9d9d9d;
            /*圆角*/
            border-radius:10px;
        }
    </style>
    <link rel="stylesheet" href="js/ol3-layerswitcher.css">
    <script src="js/ol3-layerswitcher.js"></script>
</head>
<body>
<div id="map" style="height: 100%;width: 100%;">
    <div id="map-measure">
        <button  id="measure-length" type="button" class="btn btn-info">长度测量</button>
        <button id="measure-area" class="btn btn-info">面积测量</button>
        <button id="measure-cancel" class="btn btn-info">清除</button>
    </div>
    <!--地图图层控制-->
    <div id="map-switch">
        <div>
            <input type="checkbox" name="mapswitch" value="底图点" checked="checked"> 底图点
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="底图线" checked="checked"> 底图线
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="底图面"checked="checked"> 底图面
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="沉降点" checked="checked"> 沉降点
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="水平点" checked="checked"> 水平点
        </div>

    </div>
</div>
<script>
    /*初始化地图*/
    //获取layer
    function getTdtLayer(lyr) {
        var urls=[];
        for(var i=0;i<8;i++)
        {
            urls.push( "http://t"+i+".tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}&tk=07c3369864c03fb6a162ac560811db9b")
        }
        var layer = new ol.layer.Tile({
            source: new ol.source.XYZ({
                urls:urls
            })
        });
        return layer;
    }
    var view=new ol.View({
        //center:ol.proj.transform([110,39],"EPSG:4326","EPSG:3857"),
        //center:[-1131808,605000],
        //zoom:7,
        //extent:[-1246647,456556,-1017802,722617]
    });
    var map=new ol.Map({
        layers: [
/*            getTdtLayer("vec_w"),
            getTdtLayer("cva_w")*/
        ],
        view:view,
        controls: ol.control.defaults().extend([
            /*
                        new ol.control.FullScreen(),
            */
            /*            new ol.control.MousePosition({
                            coordinateFormat: ol.coordinate.createStringXY(4),
                            projection: 'EPSG:3857',
                            className: 'custom-mouse-position',
                            target: document.getElementById('mouse-position')
                        }) ,*/
/*            new ol.control.OverviewMap({
                collapsed:false
            }),*/
            /*            new ol.control.Rotate({
                            autoHide:false
                        }),*/
            //new ol.control.ScaleLine({  }),
            //new ol.control.ZoomSlider({  }),
            //new ol.control.ZoomToExtent({  })
        ]),
        target: 'map'
    });
    var jsonlayer1,jsonlayer2;
    var baselayerpoint,baselayerpolyline,baselayerpolygon;
    view.fit([-1423386,383006,-756179,895716]);

    /*添加底图图层*/
    addBaselayers("json/东坝底图");
    /*添加自定义图层*/
    //添加第一个自定义图层
    var url1="json/东坝12.geojson";
    $.ajax({
        type: "GET",
        url: url1,
        dataType:'json',
        //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
        success: function(data){
            //create featuresource and featurelayer
            var jsonSource=new ol.source.Vector({
            });
            var features=data.features;
            for (var i=0;i<features.length;i++)
            {
                var feature=features[i];
                var newfeature=new ol.Feature({
                    geometry:new ol.geom.Point(feature.geometry.coordinates)
                });
                newfeature.set("layer",feature.properties.Layer);
                newfeature.set("text",feature.properties.Text);
                newfeature.set("vl",i);
/*                var a=newfeature.getProperties();
                console.log(a);*/
                jsonSource.addFeature(newfeature);
            }
            jsonlayer1=new ol.layer.Vector({
                source:jsonSource,
                enderMode:'image',
                style: function (feature) {
                    return styleFunction(feature,3)
                }
            });
            map.addLayer(jsonlayer1);
        }
    });
    //添加第二个自定义图层
    var url2="json/东坝42.geojson";
    $.ajax({
        type: "GET",
        url: url2,
        dataType:'json',
        //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
        success: function(data){
            //create featuresource and featurelayer
            var jsonSource=new ol.source.Vector({
            });
            var features=data.features;
            for (var i=0;i<features.length;i++)
            {
                var feature=features[i];
                var newfeature=new ol.Feature({
                    geometry:new ol.geom.Point(feature.geometry.coordinates)
                });
                newfeature.set("layer",feature.properties.Layer);
                newfeature.set("text",feature.properties.Text);
                newfeature.set("vl",i);
                /*                var a=newfeature.getProperties();
                                console.log(a);*/
                jsonSource.addFeature(newfeature);
            }
            jsonlayer2=new ol.layer.Vector({
                source:jsonSource,
                enderMode:'image',
                style: function (feature) {
                    return styleFunction(feature,4)
                }

            });
            map.addLayer(jsonlayer2);
        }
    });
    //样式函数
    function styleFunction(feature,type) {
        var text=feature.getProperties().text;
        /*        if(map.getView().getZoom()<20)
                {
                    height="";
                }*/
        var color;
        if (type==1)
        {
            color=" rgba(255,0,255,0.4)";
            return new ol.style.Style({
                image: new ol.style.Circle({
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke: new ol.style.Stroke({
                        color: color,
                        width: 1.25
                    }),
                    radius: 5
                }),
                text:new ol.style.Text({
                    text:text,
                    textAlign:"left",
                    offsetX:7,
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke:new ol.style.Stroke({
                        color:color,
                        width:1
                    }),
                    font:" 14px SimHei"
                })
            });
        }
        else if (type==2)
        {
            color=" rgba( 72, 123, 182, 1.00 )";
            return new ol.style.Style({
                image: new ol.style.RegularShape({
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke: new ol.style.Stroke({
                        color: color,
                        width: 1.25
                    }),
                    radius: 7,
                    points:4,
                    angle: Math.PI / 4
                }),
                text:new ol.style.Text({
                    text:text,
                    textAlign:"left",
                    offsetX:7,
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke:new ol.style.Stroke({
                        color:color,
                        width:1
                    }),
                    font:" 15px SimHei"
                })
            });
        }
        else if (type==3)
        {
            color=" rgba(255,0,255,0.4)";
            return new ol.style.Style({
                image: new ol.style.RegularShape({
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke: new ol.style.Stroke({
                        color: color,
                        width: 1.25
                    }),
                    radius: 7,
                    points:3,
                    //rotation: Math.PI / 4,
                    //angle:0
                }),
                text:new ol.style.Text({
                    text:text,
                    textAlign:"left",
                    offsetX:7,
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke:new ol.style.Stroke({
                        color:color,
                        width:1
                    }),
                    font:" 15px SimHei"
                })
            });
        }
       else if (type==4)
        {
            color=" rgba( 72, 123, 182, 1.00 )";
            return new ol.style.Style({
                image: new ol.style.Icon({
                    src:"img/icon1.png",
                    //size:[20,20]
                    scale:0.3,
                    rotation: Math.PI / 2
                }),
                text:new ol.style.Text({
                    text:text,
                    textAlign:"left",
                    offsetX:7,
                    fill: new ol.style.Fill({
                        color: color
                    }),
                    stroke:new ol.style.Stroke({
                        color:color,
                        width:1
                    }),
                    font:" 15px SimHei"
                })
            });
        }

    }

    /*矢量测量草图图层*/
    var measureSource=new ol.source.Vector();
    var mmeasureVectorlayer = new ol.layer.Vector({
        source:measureSource,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });
    map.addLayer(mmeasureVectorlayer);
    /*********************************************************************************************************************/
    /*添加overlay*/
    var popup=new Popup(map);
    /*地图点击事件select方式*/
    var selectSingleClick = new ol.interaction.Select(
        {
            layers:function (layer) {
                if (layer==jsonlayer1||layer==jsonlayer2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    );
    map.addInteraction(selectSingleClick);
    selectSingleClick.on('select', function(e) {
        var features=e.target.getFeatures().getArray();
        if (features.length>0)
        {
            var feature=features[0];
            var geometry=feature.getGeometry();
            var properties=feature.getProperties();
            if(geometry.getType()=="Point")
            {
                popup.show(
                    "基本信息",
                    "图层："+properties.layer+"<br>"+"编号："+properties.text+"<br>"+"数值："+properties.vl+"<br>"+"<a href='http://www.w3school.com.cn' target='_blank'>历史数据</a>",
                    geometry.getCoordinates())
            }
        }
        else
        {
            popup.hide()
        }
    });

    /*测量工具*/
    $("#map-measure button").click(function (e) {
        measureSource.clear();
        map.removeOverlay(measureOverlay);
        var type=$(this).text();
        if (type=="长度测量")
        {
            startMeasure("LineString")
            var element= document.getElementById("measure-length")

        }
        else if (type=="面积测量")
        {
            startMeasure("Polygon")
        }
        else if(type=="清除")
        {

        }
    });
    //测量逻辑
    var measureTooltipElement;
    var measureOverlay;
    function startMeasure(type) {
        var draw = new ol.interaction.Draw({
            source: measureSource,
            type: type,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    stroke: new ol.style.Stroke({
                        color: 'rgba(0, 0, 0, 0.7)'
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    })
                })
            }),
            stopClick:true,
            freehand:false
        });
        map.addInteraction(draw);
        if (measureTooltipElement) {
            measureTooltipElement.parentNode.removeChild(measureTooltipElement);
        }
        measureTooltipElement = document.createElement('div');
        measureTooltipElement.className = 'tooltip tooltip-measure';
        measureOverlay = new ol.Overlay({
            element: measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        map.addOverlay(measureOverlay);

        var listener;
        var sketch;
        draw.on('drawstart',
            function(evt) {
                map.removeInteraction(selectSingleClick);

                // set sketch
                sketch = evt.feature;

                /** @type {ol.Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;

                listener = sketch.getGeometry().on('change', function(evt) {
                    var geom = evt.target;
                    var output;
                    if (geom instanceof ol.geom.Polygon) {
                        output = formatArea(geom);
                        tooltipCoord = geom.getInteriorPoint().getCoordinates();
                    } else if (geom instanceof ol.geom.LineString) {
                        output = formatLength(geom);
                        tooltipCoord = geom.getLastCoordinate();
                    }
                    measureTooltipElement.innerHTML = output;
                    measureOverlay.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function() {
                map.addInteraction(selectSingleClick);

                measureTooltipElement.className = 'tooltip tooltip-static';
                measureOverlay.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measureTooltipElement = null;

                map.removeInteraction(draw);
            }, this);
    }
    /**
     * Format length output.
     * @param {ol.geom.LineString} line The line.
     * @return {string} The formatted length.
     */
    var formatLength = function(line) {
        //var length = ol.Sphere.getLength(line);
        var length = line.getLength();
        var output;
        if (length > 100) {
            output = (Math.round(length / 1000 * 100) / 100) +
                ' ' + 'm';
        } else {
            output = (Math.round(length * 100) / 100) +
                ' ' + 'mm';
        }
        return output;
    };

    /**
     * Format area output.
     * @param {ol.geom.Polygon} polygon The polygon.
     * @return {string} Formatted area.
     */
    var formatArea = function(polygon) {
        var area = ol.Sphere.getArea(polygon);
        //var area =polygon.getArea();
        var output;
        if (area > 10000) {
            output = (Math.round(area / 1000000 * 100) / 100) +
                ' ' + 'm<sup>2</sup>';
        } else {
            output = (Math.round(area * 100) / 100) +
                ' ' + 'mm<sup>2</sup>';
        }
        return output;
    };

    /*图层控制*/
    $('#map-switch input').change(function () {
        //var a= $(this).attr();
        var value=$(this).val();
        var ischeck=this.checked;
        switch(value)
        {
            case "底图点":
                if (ischeck==true)
                {
                    baselayerpoint.setVisible(true);
                }
                else
                {
                    baselayerpoint.setVisible(false);
                }
                break;
            case "底图线":
                if (ischeck==true)
                {
                    baselayerpolyline.setVisible(true);
                }
                else
                {
                    baselayerpolyline.setVisible(false);
                }
                break;
            case "底图面":
                if (ischeck==true)
                {
                    baselayerpolygon.setVisible(true);
                }
                else
                {
                    baselayerpolygon.setVisible(false);
                }
                break;
            case "沉降点":
                if (ischeck==true)
                {
                    jsonlayer1.setVisible(true);
                }
                else
                {
                    jsonlayer1.setVisible(false);
                }
                break;
            case "水平点":
                if (ischeck==true)
                {
                    jsonlayer2.setVisible(true);
                }
                else
                {
                    jsonlayer2.setVisible(false);
                }
                break;
            default:
                break;
        }
    });


/*    var layerSwitcher = new ol.control.LayerSwitcher();
    map.addControl(layerSwitcher);*/




    /*javascript对象与string字符串*/
    //JavaScript对象
    var people=new Object();
    people.name="xcy";
    people.age=11;
    console.log(people);
    //上下两种等价
    var people2={name:"xcy", age:22};
    console.log(people2);
    //JavaScript对象转字符串
    var peopleString=JSON.stringify(people);
    console.log("peopleString--"+peopleString)
    var peopleString2="{\"name\":\"xcy\",\"age\":11}";
    console.log("peopleString2--"+peopleString2)
    //字符串转JavaScript对象
    var peopleObject=JSON.parse(peopleString);
    console.log(peopleObject);
    var peopleObject2=JSON.parse(peopleString2);
    console.log("peopleObject2--"+peopleObject2);

    function addBaselayers(proname) {

        //点图层
        var urlpoint=proname+"point.geojson";
        $.ajax({
            type: "GET",
            url: urlpoint,
            dataType:'json',
            //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
            success: function(data){
                //create featuresource and featurelayer
                var jsonSource=new ol.source.Vector({
                });
                var features=data.features;
                for (var i=0;i<features.length;i++)
                {
                    var feature=features[i];
                    var newfeature=new ol.Feature({
                        geometry:new ol.geom.Point(feature.geometry.coordinates)
                    });
                    newfeature.set("layer",feature.properties.Layer);
                    newfeature.set("text",feature.properties.Text);
                    newfeature.set("vl",i);
                    /*                var a=newfeature.getProperties();
                                    console.log(a);*/
                    jsonSource.addFeature(newfeature);
                }
                baselayerpoint=new ol.layer.Vector({
                    source:jsonSource,
                    style: new ol.style.Style({
                        image: new ol.style.Circle({
                            fill: new ol.style.Fill({
                                color: 'rgba( 190, 207, 80, 1.00 )'
                            }),
                            stroke: new ol.style.Stroke({
                                color: 'rgba( 190, 207, 80, 1.00 )',
                                width: 1.25
                            }),
                            radius: 5
                        })
                    })
                });
                map.addLayer(baselayerpoint);
            }
        });
        //线图层
        var urlpolyline=proname+"polyline.geojson";
        $.ajax({
            type: "GET",
            url: urlpolyline,
            dataType:'json',
            //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
            success: function(data){
                //create featuresource and featurelayer
                var jsonSource=new ol.source.Vector({
                });
                var features=data.features;
                for (var i=0;i<features.length;i++)
                {
                    var feature=features[i];
                    var type=feature.geometry.type;
                    if (type=="LineString")
                    {
                        var newfeature=new ol.Feature({
                            geometry: new ol.geom.LineString(feature.geometry.coordinates)
                        });
                    }
                    else if (type=="MultiLineString")
                    {
                        var newfeature=new ol.Feature({
                            geometry: new ol.geom.MultiLineString(feature.geometry.coordinates)
                        });
                    }
                    newfeature.set("layer",feature.properties.Layer);
                    newfeature.set("text",feature.properties.Text);
                    newfeature.set("vl",i);
                    /*                var a=newfeature.getProperties();
                                    console.log(a);*/
                    jsonSource.addFeature(newfeature);



                }
                baselayerpolyline=new ol.layer.Vector({
                    source:jsonSource,
                    style:  new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'rgba( 183, 72, 75, 1.00 )',
                            width: 1.25
                        })
                    })
                });
                map.addLayer(baselayerpolyline);
            }
        });
        //面图层
        var urlpolygon=proname+"polygon.geojson";
        $.ajax({
            type: "GET",
            url: urlpolygon,
            dataType:'json',
            //data: {id:1001},//也可以是字符串链接"id=1001"，建议用对象
            success: function(data){
                //create featuresource and featurelayer
                var jsonSource=new ol.source.Vector({
                });
                var features=data.features;
                for (var i=0;i<features.length;i++)
                {
                    var feature=features[i];
                    var newfeature=new ol.Feature({
                        geometry:new ol.geom.Polygon(feature.geometry.coordinates)
                    });
                    newfeature.set("layer",feature.properties.Layer);
                    newfeature.set("text",feature.properties.Text);
                    newfeature.set("vl",i);
                    /*                var a=newfeature.getProperties();
                                    console.log(a);*/
                    jsonSource.addFeature(newfeature);
                }
                baselayerpolygon=new ol.layer.Vector({
                    source:jsonSource,
                    style:  new ol.style.Style({
                        fill:new ol.style.Fill({
                            color: '#dd942e'
                        })
                    })
                });
                map.addLayer(baselayerpolygon);
            }
        });
    }

</script>
</body>
</html>
